package com.healthcare.admin.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.healthcare.admin.pojo.Sysuser;
import com.healthcare.admin.service.SysuserService;
import com.healthcare.admin.service.impl.SysuserServiceImpl;
import com.healthcare.admin.utils.JwtUtil;
import com.healthcare.admin.utils.SHAUtils;
import com.healthcare.common.constants.ResultCodeEnum;
import com.healthcare.common.exception.KetaiException;
import com.healthcare.common.vo.Result;
import io.jsonwebtoken.Claims;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.sql.Wrapper;
import java.util.List;

/**
 * <p>
 * 后台系统用户 前端控制器
 * </p>
 *
 * @author 新华医院转诊联盟
 * @since 2020-04-12
 */
@Api(tags = "后台系统用户管理")
@RestController
@RequestMapping("/admin/user")
@CrossOrigin
public class SysuserController {

   @Resource
    private SysuserService userService;

    @ApiOperation(value = "后台用户登录")
    @PostMapping("login")
    public Result login(
            @ApiParam(name = "SysUser", value = "后台系统用户对象", required = true)
            @RequestBody Sysuser SysUser) {
        String pwd = SHAUtils.encodeData(SysUser.getPassword());
        SysUser.setPassword(pwd);
        Sysuser user = userService.findUserVoByUsernameAndPassword(SysUser);
        if (user != null) {
            String token = JwtUtil.getToken(SysUser.getUsername());
            return Result.ok().data("token", token);
        }
        return Result.error().message("帐号密码错误");
    }

    @GetMapping("info")
    @ApiOperation(value = "获取用户信息")
    public Result info(
            @ApiParam(name = "token", value = "令牌", required = true)
            @RequestParam String token) throws ServletException {

        Claims claims = JwtUtil.checkToken(token);
        String username = claims.getSubject();

        return Result.ok()
                .data("roles", claims.get("roles"))
                .data("name", username)
                .data("avatar", "https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif");
    }

    @PostMapping("logout")
    @ApiOperation(value = "用户退出")
    public Result logout(HttpServletRequest request) throws ServletException {
        String authHeader = request.getHeader("X-Token");
        System.out.println("----"+authHeader);
        if (authHeader == null) {
            throw new KetaiException(ResultCodeEnum.UNKNOWN_REASON);
        }
        //验证token
        Claims claims = JwtUtil.checkToken(authHeader);
        System.out.println(claims);
        claims.remove(claims.getSubject());

        return Result.ok();
    }


}

